package com.aigc.sclassroom.controller;

import com.aigc.sclassroom.pojo.Result;
import com.aigc.sclassroom.pojo.SysUser;
import com.aigc.sclassroom.service.UserService;
import com.aigc.sclassroom.utils.JwtUtil;
import com.aigc.sclassroom.utils.SecurityUtils;
import com.aigc.sclassroom.utils.ThreadLocalUtil;
import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Validated
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/register")
    public Result register(@Pattern(regexp ="^\\S{1,20}$")String userName, @Pattern(regexp ="^\\S{5,20}$")String password,Long roleId){
        //查询用户
        SysUser sysUser=userService.findByUserName(userName);

        //是否已存在该用户
        if(sysUser==null){
            //注册
            userService.register(userName,password);
            SysUser sysUserNew=userService.findByUserName(userName);
            userService.registerRole(sysUserNew.getUserId(),roleId);
            return Result.success();
        }else {
            return Result.error("用户已存在");
        }
    }

    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Pattern(regexp ="^\\S{1,20}$")String userName,@Pattern(regexp ="^\\S{5,20}$")String password){
        SysUser sysUser=userService.findByUserName(userName);
        if (sysUser==null){
            return Result.error("用户名错误");
        }
        //判断密码是否正确 sysUser中的password是密文
        if(SecurityUtils.matchesPassword(password,sysUser.getPassword())){
            Map<String,Object> claims = new HashMap<>();
            claims.put("id",sysUser.getUserId());
            claims.put("username",sysUser.getUserName());
            String token = JwtUtil.genToken(claims);
            System.out.println(token);

            //把token存储到redis中

            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            operations.set(token,token,12, TimeUnit.HOURS);
            // 获取用户角色信息
            Long userId = userService.getUserIdByName(userName);
            String roleKey = userService.getRoleKeyByUserId(userId);
            Map<String, Object> result = new HashMap<>();
            result.put("token", token);
            result.put("roleKey", roleKey);
            result.put("userId", userId);
            return Result.success(result);
        }
        return Result.error("密码错误");
    }

    //获取登录用户详细信息
    @GetMapping("/userInfo")
    public Result<SysUser> getUserInfo(){
        Map<String,Object> map = ThreadLocalUtil.get();
        String userName = (String)map.get("username");
        SysUser sysUser = userService.findByUserName(userName);
        return Result.success(sysUser);
    }
    //更新用户个人信息
    @PutMapping("/update")
    public Result update(@RequestBody SysUser user){
        userService.update(user);
        return Result.success();
    }

    //更新头像
    @PostMapping ("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userService.updateAvatar(avatarUrl);
        return Result.success();
    }

    //更换密码
    @PostMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        //1.校验参数
        String oldPwd = params.get("old_pwd");
        String newPwd = params.get("new_pwd");
        String rePwd = params.get("re_pwd");

        if(!StringUtils.hasLength(oldPwd)||!StringUtils.hasLength(newPwd)||!StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数");
        }
        //原密码是否正确
        //调用userService根据用户名拿到原密码，再和old_pwd对比
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String)map.get("username");
        SysUser loginUser = userService.findByUserName(username);
        if(!SecurityUtils.matchesPassword(oldPwd,loginUser.getPassword())){
            return Result.error("原密码填写不正确");
        }
        if (!rePwd.equals(newPwd)){
            return Result.error("两次次填写的新密码不一样");
        }
        //2.调用service完成密码更新
        userService.updatePwd(newPwd);
        //删除redis中对应的token
        //需要重新登录
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);
        return Result.success();
    }
}
